/**
 * Created by gray on 2019/7/25.
 */
/**
 * Created by gray on 2019/7/25.
 */
/**
 * amazonSOdetails.js
 *
 * @NAmdConfig ./configuration.json
 * @NApiVersion 2.x
 */
define(
    ['N/record', 'N/error', 'N/search','N/runtime','../common/utils'],
    function(record, error,search,runtime,utils) {

        var attribute = new Object();
        var method = new Object();

        method.getCustomerId = function(builder,order) {
            //customer customing
            builder.method.customerCustoming(order);
            if(order.customerId){
                return order.customerId;
            }else{
                return method.checkOrCreateCustomer(builder,order);
            }
        }

        //确认或者创建客户。
        method.checkOrCreateCustomer = function(builder,order){
            var customerId = method.customerExists(builder,order);
            if(customerId){
                method.useOldCustomer(builder,order,customerId);
            }else{
                customerId = method.createAndSaveCustomer(builder,order);
            }
            return customerId;
        }

        //引用已存在的用户
        method.useOldCustomer = function(builder,order,customerId){
            log.debug({title: '客户存在',details: "客户存在，引用已存在的这个客户。"});
            var rec = record.load({
                id:customerId,
                type:'customer',
                isDynamic:true
            });
            //确认地址是否重复 重复就引用 不重复就添加
            method.checkAndUpdateAddress(builder,rec,order);
            method.checkAndUpdateCurrency(rec,order);
        }

        method.createAndSaveCustomer = function(builder,order){
            log.debug({title: '客户不存在',details: "客户不存在，创建新的客户。"});
            var customer = order.customer;

            var rec = record.create({
                type: record.Type.CUSTOMER,
                isDynamic: true
            });

            rec.setValue('isperson', 'T');
            rec.setValue('firstname', customer.name);
            rec.setValue('lastname', '<>');
            rec.setValue('email', customer.email);

            var idMapValue = builder.attribute.customerIdMap_value;
            for(var key in idMapValue){
                var id = idMapValue[key];
                var value = utils.method.getJSONElementValue(order,key);
                if(value&&value!=null&&value!==""){
                    try{rec.setValue(id,value);}catch(e){}
                }
            }
            var idMapText = builder.attribute.customerIdMap_text;
            for(var key in idMapText){
                var id = idMapText[key];
                var text = utils.method.getJSONElementValue(order,key);
                if(text&&text!=null&&text!==""){
                    try{rec.setText(id,text);}catch(e){}
                }
            }
            //添加地址
            method.addAddress(builder,rec,order);
            //增加货币
            method.checkAndUpdateCurrency(rec,order);
            customerId = rec.save();
            return customerId;
        }

        method.customerExists = function(builder,order){
            var conditions = builder.attribute.customerExistsCondition;
            log.debug({
                title: 'customer exists conditions',
                details: JSON.stringify(conditions)
            });
            var ExistsFilter = [];
            if(conditions.length&&conditions.length>0){
                for(var i=0;i<conditions.length;i++){
                    var condition = conditions[i];
                    var value ;
                    var recordId;
                    try{recordId = builder.attribute.customerIdMap_value[condition];}catch(e){};
                    if(!recordId){
                        try{recordId = builder.attribute.customerIdMap_text[condition];}catch(e){};
                    }
                    if(!recordId){
                        log.error({
                            title: 'config error',
                            details: "the customer exists condistion ["+condition+"] not in customer id map"
                        });
                        throw "config error : the customer exists condistion ["+condition+"] not in customer id map";
                    }
                    value = utils.method.getJSONElementValue(order,condition);
                    log.debug({
                        title: 'order exists condition nsid value',
                        details: condition+","+recordId+","+value
                    });
                    if(value){
                        if(ExistsFilter.length!=0){
                            ExistsFilter[ExistsFilter.length] = 'AND';
                        }
                        ExistsFilter[ExistsFilter.length] =
                            [recordId,'is',value];
                    }else{
                        throw " config error : cant find the order exists condition value [order."+condition+"] from order body";
                    }
                }
            }

            log.debug({
                title: 'customer exists filter',
                details: JSON.stringify(ExistsFilter)
            });
            var recId ;
            var customerExistsSearch = search.create({
                type:'customer',
                title: 'orderExistsSearch',
                columns: [],
                filters: ExistsFilter
            }).run().each(function (ctx) {
                recId = ctx.id;
            });
            log.debug({
                title: 'recId',
                details: JSON.stringify(recId)
            });
            return recId;
        }

        //确认地址是否重复 重复就引用 不重复就添加
        method.checkAndUpdateAddress = function(builder,customer,order) {
            var index = customer.findSublistLineWithValue({
                sublistId: 'addressbook',
                fieldId: 'label',
                value: builder.attribute.addressExistsCondition[0]
            });
            if (index >= 0) {
                //address exist, do nothing
            } else {
                method.addAddress(builder,customer,order);
            }
        }

        method.checkAndUpdateCurrency = function(customer,order){
            var currencyName = order.currency;
            try{
                var ids = utils.method.getCurrencyIdByName(currencyName);
                var hasCurrency = customer.findSublistLineWithValue({
                    sublistId: 'currency',
                    fieldId: 'currency',
                    value: ids
                });
                if (hasCurrency < 0) {
                    customer.selectNewLine('currency');
                    customer.setCurrentSublistValue('currency', 'currency', ids);
                    customer.commitLine('currency');
                }
            }catch(e){
                log.debug({title: '货币错误',details:"给客户增加货币错误:"+currencyName});
                throw e;
            }
        }

        method.addAddress = function(builder,rec,order){
            rec.selectNewLine('addressbook');
            rec.setCurrentSublistValue('addressbook', 'label',
                utils.method.getJSONElementValue(order,builder.attribute.addressExistsCondition[0]));
            rec.setCurrentSublistValue('addressbook', 'defaultshipping', true);
            rec.setCurrentSublistValue('addressbook', 'defaultbilling', true);
            var subrecord = rec.getCurrentSublistSubrecord(
                'addressbook', 'addressbookaddress');
            var idMapValue = builder.attribute.addressIdMap_value;
            for(var key in idMapValue){
                var id = idMapValue[key];
                var value = utils.method.getJSONElementValue(order,key);
                if(value&&value!=null&&value!==""){
                    try{subrecord.setValue(id,value);}catch(e){}
                }
            }
            var idMapText = builder.attribute.addressIdMap_value;
            for(var key in idMapText){
                var id = idMapText[key];
                var text = utils.method.getJSONElementValue(order,key);
                if(text&&text!=null&&text!==""){
                    try{subrecord.setText(id,text);}catch(e){}
                }
            }
            rec.commitLine('addressbook');

        }

        return {
            attribute:attribute,
            method: method
        };

    });